# -*- coding: utf-8 -*-
import MySQLdb
import logging


def query_by_sql(sql, host, port, username, password, db_name):
    try:
        conn = MySQLdb.Connect(host=host, port=port, user=username, passwd=password, db=db_name)
        cur = conn.cursor()
        cur.execute(sql)
        results = cur.fetchall()
        cur.close()
        conn.close()
        return results
    except MySQLdb.Error, e:
        logging.error(e)


def add_by_sql(sql, host, port, username, password, db_name):
    try:
        conn = MySQLdb.Connect(host=host, port=port, user=username, passwd=password, db=db_name)
        cur = conn.cursor()
        cur.execute(sql)
        conn.commit()
        cur.close()
        conn.close()
    except MySQLdb.Error, e:
        logging.error(e)


def update_by_sql(sql, host, port, username, password, db_name):
    try:
        conn = MySQLdb.Connect(host=host, port=port, user=username, passwd=password, db=db_name)
        cur = conn.cursor()
        cur.execute(sql)
        conn.commit()
        cur.close()
        conn.close()
    except MySQLdb.Error, e:
        logging.error(e)
